
package com.bear.cmcc.NetTestHTTP;

import com.bear.cmcc.NetTestHTTP.component.CityBean;
import com.bear.cmcc.NetTestHTTP.component.CountrySortBean;
import com.bear.cmcc.NetTestHTTP.component.json.respond.CountryCityFtpInfoRankRespond;
import com.bear.cmcc.NetTestHTTP.component.json.respond.GetNetDataReturnInfoRespond;
import com.bear.cmcc.NetTestHTTP.component.json.respond.NetDataDescriInfoRespond;
import com.bear.cmcc.NetTestHTTP.constant.HttpConstant;
import com.bear.cmcc.NetTestHTTP.constant.LocationConstant;
import com.bear.cmcc.NetTestHTTP.constant.MyCommonConstant;
import com.bear.cmcc.NetTestHTTP.httpUtil.HttpUtil;
import com.bear.cmcc.NetTestHTTP.ui.activity.AbstractActivity;
import com.bear.cmcc.NetTestHTTP.ui.activity.CityInfoActivity;
import com.bear.cmcc.NetTestHTTP.ui.adapter.NetSortAdapter;
import com.bear.cmcc.NetTestHTTP.ui.view.LoadingDialog;
import com.bear.cmcc.NetTestHTTP.util.CountryUtil;
import com.bear.cmcc.NetTestHTTP.util.LocationUtil;
import com.bear.cmcc.NetTestHTTP.util.MyCommonUtil;
import com.bear.cmcc.NetTestHTTP.util.SetUtil;
import com.bear.cmcc.NetTestHTTP.util.Sort2GSpeed;
import com.bear.cmcc.NetTestHTTP.util.SortTDSpeed;
import com.bear.net.httpclient.util.PhoneInfoUtils;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class NationalInfoActivity extends AbstractActivity {

    private LinearLayout lyStretch, ly_first;

    private CheckBox cbInfoSelect, cbSelect;

    private TextView allInfoTV, firstcontentTV;

    private TextView gprsSortTV, tdTV, gprsTV;

    private boolean isTdSort, is2GSort;

    private List<CountrySortBean> listRank;

    private NetSortAdapter netsortAdapter;

    private boolean isShare, isShareData;

    private ListView listViewRank;

    String showAllInfo;

    int pos;

    int refresh = 1;

    int autoLogin = 2;

    int showDialog = 3;

    int showLoadDialog = 4;

    private LoadingDialog dialog;

    /**
     * 当前手机所在的省份，通过百度定位实现。
     */
    private String currentProviceName = null;

    private Handler refreshHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == refresh) {
                // 默认降序排
                Collections.sort(listRank, new SortTDSpeed(SortTDSpeed.DOWN));
                tdTV.setText("TD " + getString(R.string.sortup));// 默认从高到低
                isTdSort = true;
                netsortAdapter.notifyDataSetChanged();
                if (showAllInfo != null) {
                    allInfoTV.setText(Html.fromHtml(showAllInfo));
                    firstcontentTV.setText(Html.fromHtml(showAllInfo));
                }

                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }

            } else if (msg.what == autoLogin) {
                String[] values = SetUtil.getLoginInfo(NationalInfoActivity.this);
                if (values != null && values.length == 2 && !TextUtils.isEmpty(values[0])
                        && !TextUtils.isEmpty(values[1])) {
                    MyCommonUtil.showMessage(NationalInfoActivity.this, R.string.auto_logining);
                    boolean result = MyCommonUtil.startAutoLogin(NationalInfoActivity.this,
                            values[0], values[1]);

                    if (!result) {
                        MyCommonUtil.showLoginDialog(NationalInfoActivity.this);
                    } else {
                        refresh();
                    }
                } else {
                    MyCommonUtil.showLoginDialog(NationalInfoActivity.this);
                }

            } else if (msg.what == showDialog) {
                MyCommonUtil.showLoginDialog(NationalInfoActivity.this);
            } else if (msg.what == showLoadDialog) {
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
            }
        }
    };

    private void startGetData(final boolean shouldFresh) {
        new Thread() {
            @Override
            public void run() {
                if (MyCommonUtil.isNetworkAviable(getApplicationContext())) {
                    refreshHandler.sendEmptyMessage(showLoadDialog);
                    setLayoutData(shouldFresh);
                    refreshHandler.sendEmptyMessage(refresh);
                }
            }
        }.start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loadBottomBar();
        choseBottomItemIndex(MyCommonConstant.COUNTRY_ACTIVITY_INDEX);
        setTitle(R.string.bottom_country);
        setContentView(R.layout.activity_national);
        
//        getPhone();       
        layoutInit();
        dialog = new LoadingDialog(this);
        dataInit();
        
        dealWithLogin();
    }

    /**
     * 出来登录。
     */
    public void dealWithLogin() {
        if (!NetworkTestApp.getApp().isHaveLogin()) {

            if (SetUtil.getIsAuToLogin(this)) {

                refreshHandler.sendEmptyMessage(autoLogin);
            } else {
                refreshHandler.sendEmptyMessage(showDialog);
            }
        } else {
            startGetData(false);
        }
    }

    private void getPhone() {
        String number = SetUtil.getTelNumber(this);
        if (number == null || number.trim().equals("")) {
            Toast.makeText(this, "开始获取你的手机号码...", Toast.LENGTH_LONG).show();
            Log.d("this", "开始获取你的手机号码...");
            PhoneInfoUtils.getPhoneNumTry(NationalInfoActivity.this,
                    new PhoneInfoUtils.GetPhoneNumSuccessCallback() {
                        public void onSuccess(String phoneNumber) {
                            Log.d("this", "获取完成" + phoneNumber);
                            if (phoneNumber != null || !phoneNumber.equals("")) {
                                SetUtil.setTelNumber(NationalInfoActivity.this, phoneNumber);
                                if (PhoneInfoUtils.isStop) {
                                    MyCommonUtil.closeTelNumberDialog();
                                }
                            } else {
                                Toast.makeText(NationalInfoActivity.this, "获取手机号码失败",
                                        Toast.LENGTH_LONG).show();
                            }
                        }

                        public void onfaill() {
                            Log.d("this", "获取失败");
                            Toast.makeText(NationalInfoActivity.this, "获取手机号码失败", Toast.LENGTH_LONG)
                                    .show();
                            MyCommonUtil.showInputTelNumberDialog(NationalInfoActivity.this);
                        }
                    });
        }
    }

    @Override
    protected void onStart() {
        choseBottomItemIndex(MyCommonConstant.COUNTRY_ACTIVITY_INDEX);
        super.onStart();
    }

    /**
     * 重载abstract 接口 屏蔽重复点击bottom按钮操作
     */
    protected void responseForCountry() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        setCurrentProviceHigltShow(null);
        // tvSignalValue.setText(String.valueOf(NetworkTestApp.getNetStrong()));
    }

    private void layoutInit() {
        setShareButton(onclick);

        lyStretch = (LinearLayout) findViewById(R.id.lyStretch);
        ((CheckBox) findViewById(R.id.cbStretch)).setOnCheckedChangeListener(onCheckedListener);
        ((LinearLayout) findViewById(R.id.ly_layout)).setOnClickListener(onClickListener);

        cbInfoSelect = (CheckBox) findViewById(R.id.cbInfoSelect);
        cbInfoSelect.setOnCheckedChangeListener(onCheckedListener);
        cbInfoSelect.setChecked(true);

        cbSelect = (CheckBox) findViewById(R.id.cbSelect);
        cbSelect.setOnCheckedChangeListener(onCheckedListener);
        gprsSortTV = (TextView) findViewById(R.id.gprsSortTV);
        tdTV = (TextView) findViewById(R.id.tdTV);
        gprsTV = (TextView) findViewById(R.id.gprsTV);
        tdTV.setOnClickListener(onclick);
        gprsTV.setOnClickListener(onclick);

        listViewRank = (ListView) findViewById(R.id.listViewRank);
        listViewRank.setOnItemClickListener(onItemClickListener);
        listViewRank.setOnScrollListener(scrollListener);
        listRank = new ArrayList<CountrySortBean>();

        netsortAdapter = new NetSortAdapter(this, listRank);
        listViewRank.setAdapter(netsortAdapter);

        ly_first = (LinearLayout) findViewById(R.id.ly_first);
        allInfoTV = (TextView) findViewById(R.id.allcontent);
        firstcontentTV = (TextView) findViewById(R.id.firstcontent);
        firstcontentTV.setOnClickListener(onClickListener);
        allInfoTV.setOnClickListener(onClickListener);
    }

    /**
     * 切换分享和不分享界面
     */
    private void shareLayout() {
        if (isShare) {
            cbInfoSelect.setVisibility(View.VISIBLE);
            cbSelect.setVisibility(View.VISIBLE);
            gprsSortTV.setVisibility(View.GONE);
            netsortAdapter.setSelect(isShare);
        } else {
            cbInfoSelect.setVisibility(View.GONE);
            cbSelect.setVisibility(View.GONE);
            gprsSortTV.setVisibility(View.INVISIBLE);
            netsortAdapter.setSelect(isShare);
        }
    }

    private void dataInit() {
        initializeListener();
        isShare = false;
        isTdSort = false;
        is2GSort = false;
        shareLayout();
        // startGetData(false);
    }

    private void initializeListener() {
        // IntentFilter filter = new IntentFilter();
        // filter.addAction(MyCommonConstant.PrivateActionName.NET_WORK_TEST_DATA_DOWN);
        // this.registerReceiver(serviceReceiver, filter);
    }

    @Override
    protected void onDestroy() {
        try {
            // unregisterReceiver(serviceReceiver);
        } catch (Exception e) {
        }
        super.onDestroy();
    }

    private OnClickListener onclick = new OnClickListener() {
        @SuppressWarnings("unchecked")
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_right:
                    if (isShare) {
                        String shareData = setShareData();
                        if (isShareData) {
                            try {
                                MyCommonUtil.share(NationalInfoActivity.this,
                                        getString(R.string.share), shareData);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        isShare = false;
                    } else {
                        cbInfoSelect.setChecked(true);
                        // cbSelect.setChecked(true);
                        if (netsortAdapter.getCount() > 0)
                            netsortAdapter.setAllSelect(false);
                        netsortAdapter.setCurrentProvinceCheck();
                        isShare = true;
                    }
                    shareLayout();
                    setCurrentProviceHigltShow(null);
                    break;
                case R.id.tdTV:
                    if (isTdSort) {
                        Collections.sort(listRank, new SortTDSpeed(SortTDSpeed.UP));
                        tdTV.setText("TD " + getString(R.string.sortdown));
                        isTdSort = false;
                    } else {
                        Collections.sort(listRank, new SortTDSpeed(SortTDSpeed.DOWN));
                        tdTV.setText("TD " + getString(R.string.sortup));
                        isTdSort = true;
                    }
                    gprsTV.setText("2G");
                    netsortAdapter.notifyDataSetChanged();
                    setCurrentProviceHigltShow(null);
                    break;
                case R.id.gprsTV:
                    if (is2GSort) {
                        Collections.sort(listRank, new Sort2GSpeed(Sort2GSpeed.UP));
                        gprsTV.setText("2G " + getString(R.string.sortdown));
                        is2GSort = false;
                    } else {
                        Collections.sort(listRank, new Sort2GSpeed(Sort2GSpeed.DOWN));
                        gprsTV.setText("2G " + getString(R.string.sortup));
                        is2GSort = true;
                    }
                    tdTV.setText("TD");
                    netsortAdapter.notifyDataSetChanged();
                    setCurrentProviceHigltShow(null);
                    break;
            }
        }

    };

    private String setShareData() {
        StringBuffer sb = new StringBuffer();

        isShareData = false;
        if (cbInfoSelect.isChecked()) {
            isShareData = true;
            if (showAllInfo == null || showAllInfo.equals(""))
                sb.append(getString(R.string.bottom_country));
            else
                sb.append(Html.fromHtml(showAllInfo));
        }
        sb.append("\n");
        for (int i = 0; i < listRank.size(); i++) {
            if (netsortAdapter.isSelected(i)) {
                isShareData = true;
                sb.append(listRank.get(i).getProvince_name());
                sb.append(" TD:");
                sb.append(listRank.get(i).getTd_downSpeed());
                sb.append(";2G:");
                sb.append(listRank.get(i).getGprs_downSpeed());
                sb.append(";");
                sb.append("\n");
            }
        }
        sb.append("--" + getString(R.string.app_name));
        return sb.toString();
    }

    private OnItemClickListener onItemClickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            if (isShare) {
                netsortAdapter.setRadioSelect(arg2);
            } else {
                ((CheckBox) findViewById(R.id.cbStretch)).setChecked(false);
                Intent it = new Intent(NationalInfoActivity.this, CityInfoActivity.class);
                String currentClickPro = listRank.get(arg2).getProvince_name();
                NetworkTestApp.getApp().setCurrentUserClickProvice(currentClickPro);
                it.putExtra("provinceName", currentClickPro);
                it.putExtra(MyCommonConstant.PROVINCE_CODE, listRank.get(arg2).getProvince_code());
                startActivity(it);
            }
        }
    };

    private OnCheckedChangeListener onCheckedListener = new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            switch (buttonView.getId()) {
                case R.id.cbSelect:
                    if (netsortAdapter.getCount() > 0)
                        netsortAdapter.setAllSelect(isChecked);
                    break;
                case R.id.cbStretch:
                    if (isChecked) {
                        lyStretch.setVisibility(View.VISIBLE);
                        ly_first.setVisibility(View.GONE);
                    } else {
                        lyStretch.setVisibility(View.GONE);
                        ly_first.setVisibility(View.VISIBLE);
                    }
                    break;
            }
        }
    };

    private OnScrollListener scrollListener = new OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            // TODO Auto-generated method stub
            switch (view.getId()) {
                case R.id.listViewRank:
                    if (lyStretch.getVisibility() == View.VISIBLE)
                        ((CheckBox) findViewById(R.id.cbStretch)).setChecked(false);
                    break;
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                int totalItemCount) {
            // TODO Auto-generated method stub

        }
    };

    private OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.ly_layout:
                    if (lyStretch.getVisibility() == View.GONE)
                        ((CheckBox) findViewById(R.id.cbStretch)).setChecked(true);
                    else
                        ((CheckBox) findViewById(R.id.cbStretch)).setChecked(false);
                    break;
                case R.id.allcontent:
                    if (lyStretch.getVisibility() == View.GONE)
                        ((CheckBox) findViewById(R.id.cbStretch)).setChecked(true);
                    else
                        ((CheckBox) findViewById(R.id.cbStretch)).setChecked(false);
                    break;
                case R.id.firstcontent:
                    if (lyStretch.getVisibility() == View.GONE)
                        ((CheckBox) findViewById(R.id.cbStretch)).setChecked(true);
                    else
                        ((CheckBox) findViewById(R.id.cbStretch)).setChecked(false);
                    break;
            }
        }
    };

    /**
     * 设置当前省份高亮显示。
     */
    protected void setCurrentProviceHigltShow(Intent intent) {
        try {
            if (intent != null) {
                currentProviceName = intent.getStringExtra(LocationConstant.PROVINCE);
            }

            if (currentProviceName == null) {
                currentProviceName = NetworkTestApp.getApp().getProviceName();
            }

            // 到这边都是来自定位的数据，如果是北京，那么就不定位
            if (currentProviceName != null) {
                if (currentProviceName.equals(NetworkTestApp.getApp().getBeijing())) {
                    currentProviceName = null;
                }
            }
            // 说明已经有用户点击，那么当前高亮要使用用来最近一次点击的省份
            String click = NetworkTestApp.getApp().getCurrentUserClickProvice();
            if (click != null) {
                currentProviceName = click;
            }

            if (currentProviceName != null && listRank != null && listRank.size() > 0) {
                pos = netsortAdapter.setSelectShowItemt(currentProviceName);
                if (pos < 0 || pos >= listRank.size()) {
                    return;
                }
                if (listRank.get(pos) != null) {
                    listRank.get(pos).setSelect(true);
                    if (pos >= 0) {
                        netsortAdapter.notifyDataSetChanged();
                        // 由于要把当前省份显示在中间
                        if (pos > 2) {
                            pos = pos - 2;
                        } else {
                            pos = 0;
                        }
                        listViewRank.setSelection(pos);
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 由于网络变化，而触发的刷新。
     * 
     * @param isConnect
     */
    @Override
    protected void refreshByNetworkChange(boolean isConnect) {

        if (currentProviceName == null && isConnect) {
            LocationUtil.getCurrentCity(this);
        }
    }

    @Override
    protected void locationSuccess(Intent intent) {
        setCurrentProviceHigltShow(intent);
    }

    private void setLayoutData(boolean isShouldFresh) {
        try {
            ArrayList<CountrySortBean> countrys = null;
            GetNetDataReturnInfoRespond info = null;
            ArrayList<CityBean> citys = null;

            countrys = NetworkTestApp.getApp().getCountrys();
            info = NetworkTestApp.getApp().getCountryInfo();

            CountryCityFtpInfoRankRespond respondTop = NetworkTestApp.getApp().getTopTDCity();

            if (isShouldFresh || (countrys == null || info == null || respondTop == null)
                    || (respondTop.getErrorCode() != HttpConstant.CODE_SUCCESS)) {
                countrys = CountryUtil.getSortCountryData(NationalInfoActivity.this);
                NetworkTestApp.getApp().setCountrys(countrys);
                info = HttpUtil.getRegionNetInfo(NationalInfoActivity.this, HttpConstant.COUNTRY,
                        "");
                NetworkTestApp.getApp().setCountryInfo(info);

                respondTop = CountryUtil.getTop10_TD_cityAdater(this, true,
                        HttpConstant.TOTAL_COUNT);

            }

            if (respondTop != null && respondTop.getErrorCode() == HttpConstant.CODE_SUCCESS) {
                citys = CountryUtil.changeTopRank(respondTop);
                NetworkTestApp.getApp().setTopTDCity(respondTop);
            }

            int allDevice = 0;
            int provinceNumber = 0;
            int cityNumber = 0;
            String speedTd = "0";
            String speed2G = "0";
            if (info != null && info.getErrorcode() == HttpConstant.CODE_SUCCESS) {
                NetDataDescriInfoRespond respond = info.getData();
                if (respond != null) {
                    allDevice = respond.getOnline2G() + respond.getOnlineTD();
                    provinceNumber = respond.getProvinceNumber();
                    cityNumber = respond.getCityNumber();
                    speedTd = respond.getAverageSpeedTD();
                    speed2G = respond.getAverageSpeed2G();
                }
            }

            String tempCitys = "";
            if (citys != null && citys.size() > 0) {
                Collections.sort(citys, new Comparator<CityBean>() {

                    @Override
                    public int compare(CityBean lhs, CityBean rhs) {
                        int result = -1 * (lhs.getDownSpeed() - rhs.getDownSpeed());// 降序
                        return result;
                    }

                });

                for (int i = 0; i < citys.size(); i++) {
                    if (i == 10) {
                        break;
                    }
                    tempCitys += citys.get(i).getCity_name() + ";";

                }

            }

            if (listRank != null) {
                listRank.clear();
                if (countrys != null) {
                    listRank.addAll(countrys);
                }
            }

            showAllInfo = "&nbsp;&nbsp;&nbsp;&nbsp;"
                    + CountryUtil.getSpecialGrayStr(this, getString(R.string.current_device_num))
                    + CountryUtil.getSpecialWhiteStr(this, String.valueOf(allDevice))
                    + CountryUtil.getSpecialGrayStr(this, getString(R.string.unit))
                    + CountryUtil.getSpecialWhiteStr(this, String.valueOf(provinceNumber))
                    + CountryUtil.getSpecialGrayStr(this, getString(R.string.province))
                    + CountryUtil.getSpecialWhiteStr(this, String.valueOf(cityNumber))
                    + CountryUtil.getSpecialGrayStr(this, getString(R.string.city))
                    + CountryUtil.getSpecialGrayStr(this, getString(R.string.current_device_td))
                    + CountryUtil.getSpecialWhiteStr(this, speedTd)
                    + CountryUtil.getSpecialGrayStr(this, getString(R.string.speedunit))
                    // + CountryUtil.getSpecialGrayStr(this,
                    // getString(R.string.yhbs))
                    // + CountryUtil.getSpecialWhiteStr(this,
                    // getString(R.string.yhbdvalue1))
                    // + CountryUtil.getSpecialGrayStr(this,
                    // getString(R.string.qsd))
                    // + CountryUtil.getSpecialWhiteStr(this,
                    // getString(R.string.qsvalue1))
                    // + CountryUtil.getSpecialGrayStr(this,
                    // getString(R.string.yhbe))
                    + CountryUtil.getSpecialGrayStr(this, getString(R.string.current_device_tg))
                    + CountryUtil.getSpecialWhiteStr(this, speed2G)
                    + CountryUtil.getSpecialGrayStr(this, getString(R.string.speedunit))
                    // + CountryUtil.getSpecialGrayStr(this,
                    // getString(R.string.yhbs))
                    // + CountryUtil.getSpecialWhiteStr(this,
                    // getString(R.string.yhbdvalue2))
                    // + CountryUtil.getSpecialGrayStr(this,
                    // getString(R.string.qsd))
                    // + CountryUtil.getSpecialWhiteStr(this,
                    // getString(R.string.qsvalue2))
                    // + CountryUtil.getSpecialGrayStr(this,
                    // getString(R.string.yhbe)) + "<br/>"
                    + "<br/>"
                    + CountryUtil.getSpecialGrayStr(this, getString(R.string.stretchTitleTD))
                    + CountryUtil.getSpecialGrayStr(this, tempCitys);
            // + CountryUtil.getSpecialGrayStr(this, tempCitys2);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (isShare) {
                    isShare = false;
                    shareLayout();
                    return true;
                }
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void refresh() {
        startGetData(true);
    }
}
